package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.ScheduleListAdapter;
import cn.innosmart.aq.bean.ActionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.SceneBean;
import cn.innosmart.aq.bean.ScheduleBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.manager.ScheduleManager;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.ScheduleActivity;

/**
 * Created by David on 2015/11/24.
 */
public class BoxDetailScheduleFragment extends BaseFragment {
    private final int LOADINGOVER = 0;
    private final int DATACHANGE = 7;
    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private View view;
    private ListView listView;
    private ConnectionEntity connectionEntity;
    private ScheduleListAdapter scheduleListAdapter;
    private BoxDetailAutoFragment parent;
    private AquariumBean aquariumBean;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOADINGOVER:
                    hideLoadingDialog();
                    break;
                case DATACHANGE:
                    onResume();
                    break;
            }
        }
    };
    private View.OnClickListener onModifyClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_modify:
                    modifySchedule(v);
                    break;
                case R.id.fcb_control:
                    switchSchedule(v);
                    break;
                case R.id.tv_delete:
                    ScheduleBean scheduleBean = (ScheduleBean) v.getTag();
                    showSureDeleteDialog(scheduleBean.getTitle(), scheduleBean);
                    break;
                case R.id.tv_info:
                    showAutoInfo(v);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_auto_example, container, false);
        connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
        parent = (BoxDetailAutoFragment) getParentFragment();
        aquariumBean = parent.getAquariumBean();
        listView = (ListView) view.findViewById(R.id.lv_auto);
        TextView emptyView = (TextView) view.findViewById(R.id.empty_view);
        emptyView.setText(R.string.no_schedule_data);
        listView.setEmptyView(emptyView);
        scheduleListAdapter = new ScheduleListAdapter(getActivity(), aquariumBean);
        scheduleListAdapter.setOnModifyClickListener(onModifyClickListener);
        listView.setAdapter(scheduleListAdapter);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
        startModify(parent.isModify);
    }

    @Override
    protected void refresh() {
        if (scheduleListAdapter != null){
            aquariumBean = parent.getAquariumBean();
            scheduleListAdapter.setAquariumBean(aquariumBean);
            scheduleListAdapter.refresh();
        }
    }

    @Override
    protected void startModify(boolean startModify) {
        if (scheduleListAdapter != null)
            scheduleListAdapter.startModify(startModify);
    }

    private void switchSchedule(View v) {
        final ScheduleBean scheduleBean = (ScheduleBean) v.getTag();
        showLoadingDialog(getActivity());
        if (scheduleBean.getEnabled() == 1) {
            scheduleBean.setEnabled(0);
            ScheduleManager.getInstance().Update(connectionEntity, scheduleBean.toParams(), new ScheduleManager.UpdateCallBack() {
                @Override
                public void onUpdateResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        showToast(getActivity().getString(R.string.schedule_disable));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    } else {
                        scheduleBean.setEnabled(1);
                        showToast(getActivity().getString(R.string.schedule_disable_failed));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    }
                }
            });
        } else {
            scheduleBean.setEnabled(1);
            ScheduleManager.getInstance().Update(connectionEntity, scheduleBean.toParams(), new ScheduleManager.UpdateCallBack() {
                @Override
                public void onUpdateResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        showToast(getActivity().getString(R.string.schedule_enable));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    } else {
                        scheduleBean.setEnabled(0);
                        showToast(getActivity().getString(R.string.schedule_enable_failed));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    }
                }
            });
        }
    }

    private void showSureDeleteDialog(String name, final Object object) {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(getActivity());
        customsizeDialog.setTitle(getActivity().getString(R.string.dialog_title_alert));
        customsizeDialog.setContent(String.format(getString(R.string.dialog_content_delete_sure), name));
        customsizeDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingDialog(getActivity());
                final ScheduleBean scheduleBeanDelete = (ScheduleBean) object;
                ScheduleManager.getInstance().Remove(connectionEntity, scheduleBeanDelete.toDeleteParams(), new ScheduleManager.RemoveCallBack() {
                    @Override
                    public void onRemoveResponseCallBack(int ret, String ruleid) {
                        if (ret == 0) {
                            aquariumBean.getScheduleList().remove(scheduleBeanDelete);
                            mHandler.sendEmptyMessage(DATACHANGE);
                            hideLoadingDialog();
                        }
                    }
                });
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }

    private void modifySchedule(View v) {
        ScheduleBean scheduleBean = (ScheduleBean) v.getTag();
        Intent intentSchedule = new Intent(getActivity(), ScheduleActivity.class);
        intentSchedule.putExtra("aquarium", aquariumBean.getId());
        intentSchedule.putExtra("schedule", scheduleBean.getId());
        startActivity(intentSchedule);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void showAutoInfo(View v) {
        final CustomsizeDialog autoInfoDialog = new CustomsizeDialog(getActivity());
        autoInfoDialog.setTitle(getString(R.string.auto_info_title));
        ScheduleBean scheduleBean = (ScheduleBean) v.getTag();
        spellScheduleInfo(scheduleBean, autoInfoDialog);
        autoInfoDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoInfoDialog.dismiss();
            }
        });
        autoInfoDialog.show();
    }

    private void spellScheduleInfo(ScheduleBean scheduleBean, CustomsizeDialog autoInfoDialog) {
        StringBuilder autoInfo = new StringBuilder();
        ArrayList<CommandBean> commandBeans = scheduleBean.getScheduleCommands();
        CommandBean commandBean = commandBeans.get(0);
        if (commandBean.getType().equals("scene")) {
//            SceneCommand sceneCommand = scheduleBean.getSceneCommand();
            SceneBean sceneBean = SceneBean.queryScene(commandBean.getScene_id());
            autoInfo.append(getActivity().getString(R.string.formatScheduleinfo_scene) + sceneBean.getTitle());
        } else if (commandBean.getType().equals("commands")) {
            ArrayList<ActionBean> actionBeans = commandBean.getCommand();
            ActionBean actionBean = actionBeans.get(0);
            DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(actionBean.getAddress());
            double value = actionBean.getValue();
            if (value == 255) {
                autoInfo.append(String.format(getActivity().getString(R.string.format_schedule_info_device_open), deviceBean.getName()));
            } else if (value == 0) {
                autoInfo.append(String.format(getActivity().getString(R.string.format_schedule_info_device_close), deviceBean.getName()));
            }
        }
        autoInfoDialog.setCommandContent(getString(R.string.command), autoInfo.toString());
        autoInfo.append("\r\n");
        autoInfo = new StringBuilder();
        autoInfo.append(scheduleBean.getTime());
        autoInfo.append("\r\n");
        JSONArray jsonTimeLine = scheduleBean.getTimeline();
        for (int j = 0; j < jsonTimeLine.length(); j++) {
            try {
                int startIndex = (int) jsonTimeLine.getJSONArray(j).get(0);
                switch (startIndex) {
                    case 0:
                        autoInfo.append(getString(R.string.sunday));
                        autoInfo.append(",");
                        break;
                    case 1440:
                        autoInfo.append(getString(R.string.monday));
                        autoInfo.append(",");
                        break;
                    case 2880:
                        autoInfo.append(getString(R.string.tuesday));
                        autoInfo.append(",");
                        break;
                    case 4320:
                        autoInfo.append(getString(R.string.wensday));
                        autoInfo.append(",");
                        break;
                    case 5760:
                        autoInfo.append(getString(R.string.thursday));
                        autoInfo.append(",");
                        break;
                    case 7200:
                        autoInfo.append(getString(R.string.friday));
                        autoInfo.append(",");
                        break;
                    case 8640:
                        autoInfo.append(getString(R.string.saturday));
                        autoInfo.append(",");
                        break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        autoInfo.replace(autoInfo.length() - 1, autoInfo.length(), "");
        autoInfoDialog.setValidContent(getString(R.string.worktime), autoInfo.toString());
        if (scheduleBean.getEnabled() == 1) {
            autoInfoDialog.setStatusContent(getString(R.string.status), getString(R.string.start));
        } else {
            autoInfoDialog.setStatusContent(getString(R.string.status), getString(R.string.close));
        }
        if (TextUtils.isEmpty(scheduleBean.getPns())) {
            autoInfoDialog.setPushContent(getActivity().getString(R.string.push_status), getActivity().getString(R.string.close));
        } else {
            autoInfoDialog.setPushContent(getActivity().getString(R.string.push_status), getActivity().getString(R.string.open));
        }
        if (scheduleBean.pns_priority != 0)
            autoInfoDialog.setImportanceContent(getActivity().getString(R.string.alarm_priority_title), getActivity().getString(priorityStrIds[scheduleBean.pns_priority]));

    }
}
